package com.yifushidai.api;

import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.IcBind;
import com.yifushidai.entity.IcEntity;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.mapper.IcEntityMapper;
import com.yifushidai.service.IcBindService;
import com.yifushidai.utils.ApiBaseAction;
import com.yifushidai.utils.ErrorCodeEnum;
import com.yifushidai.utils.R;
import com.yifushidai.utils.ShisuMinaPushUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "IC卡绑定")
@RequestMapping("/api/ic")
public class IcBindController extends ApiBaseAction {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IcBindService icBindService;
    @Autowired
    private IcEntityMapper icMapper;
    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;

    @PostMapping("/addIc")
    @ApiOperation(value = "添加IC卡绑定（扫码）", notes = "可选参数expireDate，格式为：yyyy-MM-dd HH:mm:ss" +
            "\n\n特别注意以下重要规则：" +
            "\n\n1. 不传expireDate参数，绑定的IC卡为长期有效；" +
            "\n\n2. 传入expireDate有效参数时，有效时间内均可使用绑定的IC卡开门，超时则无法开门。")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "mac", value = "联网盒mac", required = true),
            @ApiImplicitParam(paramType = "form", name = "icNo", value = "ic卡mac", required = true),
            @ApiImplicitParam(paramType = "form", name = "icType", value = "绑定类型(0=房东卡,1=用户卡1,2=用户卡2)", required = true),
            @ApiImplicitParam(paramType = "form", name = "expireDate", value = "失效时间", required = false, dataType = "date-time"),
            @ApiImplicitParam(paramType = "form", name = "mark", value = "备注", required = false),
    })
    public R addIc(@ModelAttribute IcBind record) throws Exception {
//        String icNo2 = AesCbc.decrypt(icNo);//取消加密
        if (record.getExpireDate() != null && record.getExpireDate().getTime() <= new Date().getTime()) {
            return R.error("失效时间设置有误");
        }
        if (!record.getIcNo().matches("^\\w{8}$") || !record.getIcType().matches("^[012]$")) {
            return R.error(ErrorCodeEnum.ARGUMENT_VALIDATION);
        }
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(record.getMac()).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        // TODO 取消IC卡常量库比对，防止生产IC厂家更换等导致IC卡号重复，需要解决卡号显示问题
        IcEntity icEntity = icMapper.selectByIcNo(record.getIcNo());
        if (icEntity == null) {
            return R.error(ErrorCodeEnum.DATA_NULL);
        }
        record.setIcId(icEntity.getId());
        if (!icBindService.selectByMacAndIcType(record).isEmpty()) {
            return R.error(ErrorCodeEnum.ICCARD_TYPE_DUPLICATE);
        }
        if (!icBindService.selectByMacAndIcNo(record).isEmpty()) {
            return R.error(ErrorCodeEnum.DATA_DUPLICATE);
        }
//        List<IcBind> list = icBindService.queryListByMac(record.getMac());
//        if (list.size() >= 3) {
//            return R.error(ErrorCodeEnum.ICCARD_MAX_BIND);
//        }

        Object res = ShisuMinaPushUtils.push(record.getMac(), "icBind:" + record.getIcNo() + "_" + record.getIcType());
        if ("OK".equals(res)) {
            if (icBindService.saveNotNull(record) > 0) {
                if (record.getExpireDate() != null) {
                    String key = "IC_" + record.getMac() + "_" + record.getIcType();
                    ValueOperations<String, IcBind> operations = redisTemplate.opsForValue();
                    operations.set(key, record);
                    redisTemplate.expireAt(key, record.getExpireDate());
                }
                return R.ok().put(record);
            } else {
                return R.error(ErrorCodeEnum.DATASOURCE_ERROR);
            }
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }

    @PostMapping("/addByIcId")
    @ApiOperation(value = "添加IC卡绑定（输入卡号）", notes = "可选参数expireDate，格式为：yyyy-MM-dd HH:mm:ss" +
            "\n\n特别注意以下重要规则：" +
            "\n\n1. 不传expireDate参数，绑定的IC卡为长期有效；" +
            "\n\n2. 传入expireDate有效参数时，有效时间内均可使用绑定的IC卡开门，超时则无法开门。")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "mac", value = "联网盒mac", required = true),
            @ApiImplicitParam(paramType = "form", name = "icId", value = "ic卡号", required = true),
            @ApiImplicitParam(paramType = "form", name = "icType", value = "绑定类型(0=房东卡,1=用户卡1,2=用户卡2)", required = true),
            @ApiImplicitParam(paramType = "form", name = "expireDate", value = "失效时间", required = false, dataType = "date-time"),
            @ApiImplicitParam(paramType = "form", name = "mark", value = "备注", required = false),
    })
    public R addByIcId(@ModelAttribute IcBind record) throws Exception {
//        String icNo2 = AesCbc.decrypt(icNo);//取消加密
        if (record.getExpireDate() != null && record.getExpireDate().getTime() <= new Date().getTime()) {
            return R.error("失效时间设置有误");
        }
        if (!record.getIcType().matches("^[012]$")) {
            return R.error(ErrorCodeEnum.ARGUMENT_VALIDATION);
        }
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(record.getMac()).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        // TODO 取消IC卡常量库比对，防止生产IC厂家更换等导致IC卡号重复，需要解决卡号显示问题
        IcEntity icEntity = icMapper.selectByPrimaryKey(record.getIcId());
        if (icEntity == null) {
            return R.error(ErrorCodeEnum.DATA_NULL);
        }
        record.setIcNo(icEntity.getIcNo());
        if (!icBindService.selectByMacAndIcType(record).isEmpty()) {
            return R.error(ErrorCodeEnum.ICCARD_TYPE_DUPLICATE);
        }
        if (!icBindService.selectByMacAndIcNo(record).isEmpty()) {
            return R.error(ErrorCodeEnum.DATA_DUPLICATE);
        }
//        List<IcBind> list = icBindService.queryListByMac(record.getMac());
//        if (list.size() >= 3) {
//            return R.error(ErrorCodeEnum.ICCARD_MAX_BIND);
//        }

        Object res = ShisuMinaPushUtils.push(record.getMac(), "icBind:" + record.getIcNo() + "_" + record.getIcType());
        if ("OK".equals(res)) {
            if (icBindService.saveNotNull(record) > 0) {
                if (record.getExpireDate() != null) {
                    String key = "IC_" + record.getMac() + "_" + record.getIcType();
                    ValueOperations<String, IcBind> operations = redisTemplate.opsForValue();
                    operations.set(key, record);
                    redisTemplate.expireAt(key, record.getExpireDate());
                }
                return R.ok().put(record);
            } else {
                return R.error(ErrorCodeEnum.DATASOURCE_ERROR);
            }
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }

    @ApiOperation(value = "查询IC卡绑定（列表）")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "mac", value = "联网盒mac", required = true),
    })
    @PostMapping("/queryIc")
    public R queryList(String mac) {
        return R.ok().put(icBindService.queryListByMac(mac));
    }

    @ApiOperation(value = "删除IC卡绑定")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "mac", value = "联网盒mac", required = true),
            @ApiImplicitParam(paramType = "form", name = "icType", value = "ic卡类型", required = true),
    })
    @PostMapping("/delIc")
    public R delete(@ModelAttribute IcBind record) throws Exception {
        if (!record.getIcType().matches("^[012]$")) {
            return R.error(ErrorCodeEnum.ARGUMENT_VALIDATION);
        }
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(record.getMac()).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);

        Object  res = ShisuMinaPushUtils.push(record.getMac(), "icUnbind:" + record.getIcType());
        if ("OK".equals(res)) {
            if (icBindService.delete(record) > 0) {
                return R.ok();
            } else {
                return R.error(ErrorCodeEnum.DATASOURCE_ERROR);
            }
        } else {
            return R.error(ErrorCodeEnum.MINA_PUSH_ERROR);
        }
    }

//    @PostMapping("/queryIc")
//    @ApiOperation(value = "ic卡查询接口", notes = "ic卡查询", produces = MediaType.APPLICATION_JSON_VALUE)
//    public R queryIc(@ApiParam("锁mac") @RequestParam String mac,
//                     @ApiParam("起始页") @RequestParam int pageIndex,
//                     @ApiParam("页大小") @RequestParam int pageSize) {
//        Map<String, Object> params = new LinkedHashMap<>();
//        params.put("page", pageIndex);
//        params.put("limit", pageSize);
//        params.put("offset", (pageIndex - 1) * pageSize);
//        params.put("mac", mac);
//        Query query = new Query(params);
//        List<IcBind> icvos = icBindService.queryIc(query);
//        int total = icBindService.queryIcTotal(query);
//        PageUtils pageUtil = new PageUtils(icvos, total, query.getLimit(), query.getPage());
//        return R.ok().put("datas", pageUtil);
//    }
//
//    //客户ic补卡请求 (暂时没有 ，直接打电话，然后插数据库)
//    @PostMapping("/updateIc")
//    @ApiOperation(value = "客户ic补卡请求接口", notes = "客户ic补卡请求", produces = MediaType.APPLICATION_JSON_VALUE)
//    public R updateIc(@ApiParam("锁mac") @RequestParam String mac,
//                      @ApiParam("ic卡名称") @RequestParam String name) throws ParseException {
//        Boolean flag = icBindService.updateIc(mac, name);
//        if (flag) {
//            return R.ok();
//        }
//        return R.error();
//    }

}
